//Given an array of integers nums and an integer k, return the total number of 
//continuous subarrays whose sum equals to k. 
//
// 
// Example 1: 
// Input: nums = [1,1,1], k = 2
//Output: 2
// Example 2: 
// Input: nums = [1,2,3], k = 3
//Output: 2
// 
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 2 * 10⁴ 
// -1000 <= nums[i] <= 1000 
// -10⁷ <= k <= 10⁷ 
// 
// Related Topics Array Hash Table Prefix Sum 👍 9714 👎 322


package leetcode.editor.en;

import java.util.HashMap;
import java.util.Map;

public class _560_SubarraySumEqualsK {
    public static void main(String[] args) {
        Solution solution = new _560_SubarraySumEqualsK().new Solution();
        int i = solution.subarraySum(new int[]{1, 1, 1}, 2);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int subarraySum(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, 1);

            int preSum = 0;
            int c = 0;
            for (int num : nums) {
                preSum+=num;
                if (map.containsKey(preSum-k)) {
                    c+=map.get(preSum-k);
                }
                map.put(preSum, map.getOrDefault(preSum, 0)+1);
            }
            return c;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}